"""
Case Type   : 函数支持指定并行相关参数
Case Name   : 支持游标并行--声明游标检索数据行的方式为no scrol，游标中的查询支持SMP计
              划，通过hint将query_dop设置>1
Create At   : 2024/10/12
Owner       : @kyleze
Description :
    1.创建测试表
    2.设置查看游标并行计划的参数并执行测试sql
    3.清理环境
Expect      :
    1.成功
    2.支持游标并行
    3.成功
History     :
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant


class ParallelEnable(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.table_name = 't_parallel_test005'
        self.cursor_name = 'c_parallel_test005'

    def test_paralle(self):
        step = '----step1:创建测试表 expect:成功----'
        self.log.info(step)
        create_sql = f'drop table if exists {self.table_name};' \
                     f'create table {self.table_name}(a int, b int, c int, ' \
                     f'd bigint);' \
                     f'insert into {self.table_name} values(' \
                     f'generate_series(1, 10000000), ' \
                     f'generate_series(1, 1000000), generate_series(1, 2), ' \
                     f'generate_series(1, 500000));analyze {self.table_name};'
        create_res = self.primary_sh.execut_db_sql(create_sql)
        self.log.info(create_res)
        self.assertIn(
            self.constant.CREATE_TABLE_SUCCESS, create_res, '执行失败' + step)
        self.assertIn(
            self.constant.INSERT_SUCCESS_MSG, create_res, '执行失败' + step)

        step = '----step2:设置查看游标并行计划的参数并执行测试sql expect:成功----'
        self.log.info(step)
        tra_sql = f'set enable_auto_explain=on;set auto_explain_level=notice;' \
                  f'explain (costs off) select /*+ set(query_dop 10) */ * ' \
                  f'from {self.table_name}; begin;declare {self.cursor_name} ' \
                  f'no scroll cursor for select /*+ set(query_dop 10) */ * ' \
                  f'from {self.table_name};fetch {self.cursor_name};end;'
        transaction_res = self.primary_sh.execut_db_sql(tra_sql)
        self.log.info(transaction_res)
        self.assertEqual(
            2, transaction_res.count("dop: 1/10"), '执行失败' + step)

    def tearDown(self):
        self.log.info('----清理环境----')
        result = self.primary_sh.execut_db_sql(f'drop table {self.table_name};')
        self.log.info(result)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, result, '删表失败')
        self.log.info(f'----{os.path.basename(__file__)} end----')
